package com.cincc.taofangwang.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.cincc.taofangwang.R;
import com.cincc.taofangwang.adapter.RecordAdapter;
import com.cincc.taofangwang.common.MyUtils;
import com.cincc.taofangwang.common.OkHttpUtils;
import com.cincc.taofangwang.constant.CallConstant;
import com.cincc.taofangwang.model.RecordModel;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

public class RecordFragment extends Fragment {
    private static final String TAG = "RecordFragment";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_record, container, false);
        initView(view);
        return view;
    }

    List<RecordModel> list = new ArrayList<>();
    RecordAdapter recordAdapter;
    SmartRefreshLayout refreshLayout;
    BottomSheetDialog bottomSheetDialog;

    private void initView(View view) {
        Toolbar toolbar = view.findViewById(R.id.toolbar);
        int statusBarHeight = ImmersionBar.getStatusBarHeight(this);
        AppBarLayout.LayoutParams lp = (AppBarLayout.LayoutParams) toolbar.getLayoutParams();
        lp.topMargin = statusBarHeight + 10;
        TextView title = view.findViewById(R.id.title_text);
        title.setText("跟进记录");

        ImageView quitImg = view.findViewById(R.id.quit_img);
        quitImg.setOnClickListener(v -> quit());

        RecyclerView recyclerView = view.findViewById(R.id.recyclerView_record);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        recordAdapter = new RecordAdapter(requireActivity(), list);
        recordAdapter.setCallBack(index -> {
            showForm(list.get(index));
        });
        recordAdapter.setClickBtnBack(i -> {
            if (i == 1) {
                showBeginDialog();
            } else if (i == 2) {
                showEndDialog();
            } else if (i == 3) {
                showPurpose();
            } else if (i == 4) {
                showStatus();
            } else if (i == 5) {
                search(true);
            }
        });
        recordAdapter.setOnTextChangeBack(i -> {
            if (list.size() > 0) {
                list.get(0).searchNumber = i;
            }
        });
        refreshLayout.setOnRefreshListener(refreshLayout12 -> search(true));
        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> search(false));
        recyclerView.setAdapter(recordAdapter);

        initTime();
    }

    private void refreshUI(JSONArray array) {
        try {
            for (int i = 0; i < array.length(); i++) {
                RecordModel model = new RecordModel(
                        array.getJSONObject(i).getString("sv_name"),
                        array.getJSONObject(i).getString("phone_no"),
                        array.getJSONObject(i).getString("yixiang"),
                        array.getJSONObject(i).getString("zhunquexing"),
                        array.getJSONObject(i).getString("yixiang_fmt"),
                        array.getJSONObject(i).getString("zhunquexing_fmt"),
                        array.getJSONObject(i).getString("xingbie"),
                        array.getJSONObject(i).getString("text_z"),
                        array.getJSONObject(i).getString("cust_group_name"),
                        array.getJSONObject(i).getString("cust_group_id"),
                        array.getJSONObject(i).getString("order_id"),
                        array.getJSONObject(i).getString("reserve"),
                        array.getJSONObject(i).getString("coutomer_iphone"),
                        array.getJSONObject(i).getString("batch_name"),
                        array.getJSONObject(i).getString("cust_type")

                );
                list.add(model);
            }
            start = list.size() - 1;
            recordAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //每次加载数量
    int limit = 10;
    //加载位置
    int start = 0;

    private void search(boolean isRefresh) {
        try {
            if (isRefresh) {
                start = 0;
                if (list.size() > 1) {
                    list.subList(1, list.size()).clear();
                }
            }
            String purpose = list.get(0).searchPurpose;
            String status = list.get(0).searchStatus;
            String number = list.get(0).searchNumber;

            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("order_created_time_FROM", MyUtils.getTimeStr(list.get(0).searchBeginTime));
            c.put("order_created_time_TO", MyUtils.getTimeStr(list.get(0).searchEndTime));
            if (!TextUtils.isEmpty(number))
                c.put("phone_no", number);
            if (!TextUtils.isEmpty(purpose))
                c.put("yixiang", (Arrays.asList(CallConstant.purposeList).indexOf(purpose) + 1) + "");
            if (!TextUtils.isEmpty(status))
                c.put("zhunquexing", (Arrays.asList(CallConstant.statusList).indexOf(status) + 1) + "");
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Order");
            jsonObject.put("act", "query");
            jsonObject.put("limit", limit);
            jsonObject.put("start", start);
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            searchRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void searchRequest(String data) {
        Log.e(TAG, "searchRequest: " + data);
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        requireActivity().runOnUiThread(() -> refreshUI(data1));
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show());
            }
        });
    }


    private void getXPhone(RecordModel model) {
        try {
            JSONArray array = new JSONArray();
            JSONObject c = new JSONObject();
            c.put("vcc_id", CallConstant.VCCID);
            c.put("calling_number", CallConstant.NAME);
            c.put("called_number", model.number);
            array.put(c);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data", array);
            jsonObject.put("id", "Task");
            jsonObject.put("act", "setXPhone");
            jsonObject.put("time", MyUtils.getCurrentTime());
            jsonObject.put("token", CallConstant.TOKEN);
            getXPhoneRequest(jsonObject.toString());
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getXPhoneRequest(String data) {
        Log.e(TAG, "getXPhoneRequest: " + data);
        BasePopupView show = new XPopup.Builder(requireActivity()).asLoading().show();
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        JSONArray data1 = jsonObject.getJSONArray("data");
                        String xPhone = data1.getJSONObject(0).getString("xphone");
                        jumpDial(xPhone);
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    requireActivity().runOnUiThread(show::dismiss);
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                    show.dismiss();
                });
            }
        });
    }

    private void saveForm(RecordModel model) {
        try {
            String status = statusEdit.getText().toString();
            if (TextUtils.isEmpty(status)) {
                Toast.makeText(requireActivity(), "请选择数据准确性", Toast.LENGTH_SHORT).show();
            } else {
                JSONArray array = new JSONArray();
                JSONObject c = new JSONObject();
                c.put("cust_group_id", model.custGroupID);
                c.put("cust_group_name", model.custGroupName);
                c.put("order_id", model.orderID);

                c.put("sv_name", nameEdit.getText().toString());//姓名
                c.put("text_z", remarkEdit.getText().toString());//备注
                c.put("xingbie", sexEdit.getText().toString().length() > 0 ? Arrays.asList(CallConstant.sexList).indexOf(sexEdit.getText().toString()) : "");//性别 男：0 女：1
                c.put("yixiang", purposeEdit.getText().toString().length() > 0 ? (Arrays.asList(CallConstant.purposeList).indexOf(purposeEdit.getText().toString()) + 1) + "" : "");//意向 +1
                c.put("zhunquexing", (Arrays.asList(CallConstant.statusList).indexOf(status) + 1) + "");//准确性+1

                array.put(c);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data", array);
                jsonObject.put("id", "Order");
                jsonObject.put("act", "save");
                jsonObject.put("time", MyUtils.getCurrentTime());
                jsonObject.put("token", CallConstant.TOKEN);
                saveFormRequest(jsonObject.toString());
            }
        } catch (Exception e) {
            Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void saveFormRequest(String data) {
        Log.e(TAG, "saveFormRequest: " + data);
        BasePopupView show = new XPopup.Builder(requireActivity()).asLoading().show();
        OkHttpUtils.httpPost(CallConstant.REQUEST_PATH, data, new HashMap<>(), new OkHttpUtils.ICallBack() {
            @Override
            public void onSuccessful(Call call, String data) {
                Log.e(TAG, "onSuccessful: " + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int code = jsonObject.getInt("response_code");
                    String msg = jsonObject.getString("response_msg");
                    if (code == 0) {
                        search(true);
                    } else {
                        requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), msg, Toast.LENGTH_SHORT).show());
                    }
                } catch (JSONException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), e.getMessage(), Toast.LENGTH_SHORT).show());
                } finally {
                    requireActivity().runOnUiThread(() -> {
                        show.dismiss();
                        closeForm();
                    });
                }
            }

            @Override
            public void onFailure(Call call, String errorMsg) {
                Log.e(TAG, "onFailure: " + errorMsg);
                requireActivity().runOnUiThread(() -> {
                    Toast.makeText(requireActivity(), errorMsg, Toast.LENGTH_SHORT).show();
                    show.dismiss();
                });
            }
        });
    }


    private void showBeginDialog() {
        new CardDatePickerDialog.Builder(requireActivity())
                .setTitle("请选择开始时间")
                .setOnChoose("确定", aLong -> {
                    Log.e(TAG, "showBeginDialog: " + aLong);
                    list.get(0).searchBeginTime = aLong;
                    recordAdapter.notifyItemChanged(0);
                    return null;
                }).setDefaultTime(list.get(0).searchBeginTime).build().show();
    }

    private void showEndDialog() {
        new CardDatePickerDialog.Builder(requireActivity())
                .setTitle("请选择结束时间")
                .setOnChoose("确定", aLong -> {
                    Log.e(TAG, "showBeginDialog: " + aLong);
                    list.get(0).searchEndTime = aLong;
                    recordAdapter.notifyItemChanged(0);
                    return null;
                }).setDefaultTime(list.get(0).searchEndTime).build().show();
    }

    private void showStatus() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择客户状态", CallConstant.statusList,
                        (position, text) -> {
                            list.get(0).searchStatus = text;
                            recordAdapter.notifyItemChanged(0);
                        })
                .show();
    }

    private void showPurpose() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择客户意向", CallConstant.purposeList,
                        (position, text) -> {
                            list.get(0).searchPurpose = text;
                            recordAdapter.notifyItemChanged(0);
                        })
                .show();
    }

    private void showSex1() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择性别", CallConstant.sexList,
                        (position, text) -> sexEdit.setText(text))
                .show();
    }

    private void showStatus1() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择数据准确性", CallConstant.statusList,
                        (position, text) -> statusEdit.setText(text))
                .show();
    }

    private void showPurpose1() {
        new XPopup.Builder(requireActivity()).asCenterList("请选择客户意向", CallConstant.purposeList,
                        (position, text) -> purposeEdit.setText(text))
                .show();
    }

    private void quit() {
        new XPopup.Builder(getContext()).asConfirm("提示", "确定要退出登录吗？",
                        () -> {
                            Intent i = new Intent(requireActivity(), LoginActivity.class);
                            requireActivity().startActivity(i);
                            requireActivity().finish();
                        })
                .show();
    }

    private void showForm(RecordModel model) {
        bottomSheetDialog = new BottomSheetDialog(requireActivity(), R.style.BottomSheetDialog);
        View bottomView = LayoutInflater.from(requireContext()).inflate(R.layout.home_form_popup, null);
        initForm(bottomView, model);
        bottomSheetDialog.setContentView(bottomView);
        bottomSheetDialog.show();
    }


    TextView sexEdit, taskNumberEdit,statusEdit, purposeEdit;
    EditText nameEdit, remarkEdit;

    private void initForm(View view, RecordModel model) {
        nameEdit = view.findViewById(R.id.edit_name);
        sexEdit = view.findViewById(R.id.edit_sex);
        taskNumberEdit = view.findViewById(R.id.edit_task_number);
        statusEdit = view.findViewById(R.id.edit_status);
        purposeEdit = view.findViewById(R.id.edit_purpose);
        remarkEdit = view.findViewById(R.id.edit_remark);
        RelativeLayout callLayout = view.findViewById(R.id.call_relayout);
        RelativeLayout saveLayout = view.findViewById(R.id.save_relayout);
        TextView statusText = view.findViewById(R.id.status_tv);
        Spanned spanned = Html.fromHtml("<font color=\"#FF0000\">" + "*" + "</font>" + "客户状态");
        statusText.setText(spanned);
        taskNumberEdit.setText(model.number);

        nameEdit.setText(model.name);
        remarkEdit.setText(model.remark);
        sexEdit.setText(TextUtils.isEmpty(model.sex) ? "" : CallConstant.sexList[Integer.parseInt(model.sex)]);
        statusEdit.setText(TextUtils.isEmpty(model.status) ? "" : CallConstant.statusList[Integer.parseInt(model.status) - 1]);
        purposeEdit.setText(TextUtils.isEmpty(model.purpose) ? "" : CallConstant.purposeList[Integer.parseInt(model.purpose) - 1]);


        TextView iphoneEdit = view.findViewById(R.id.edit_iphpne);
        TextView reverseEdit = view.findViewById(R.id.edit_reverse);
        TextView batchEdit = view.findViewById(R.id.edit_batch);
        TextView custTypeEdit = view.findViewById(R.id.edit_cust_type_tv);

        if (TextUtils.isEmpty(model.coutomerIPhone)) {
            TextView iphoneText = view.findViewById(R.id.iphone_tv);
            iphoneText.setVisibility(View.GONE);
            iphoneEdit.setVisibility(View.GONE);
        } else {
            iphoneEdit.setText(model.coutomerIPhone);
        }

        if (TextUtils.isEmpty(model.reserve)) {
            TextView reverseText = view.findViewById(R.id.reverse_tv);
            reverseText.setVisibility(View.GONE);
            reverseEdit.setVisibility(View.GONE);
        } else {
            reverseEdit.setText(model.reserve);
        }

        if (TextUtils.isEmpty(model.batchName)) {
            TextView batchText = view.findViewById(R.id.batch_tv);
            batchText.setVisibility(View.GONE);
            batchEdit.setVisibility(View.GONE);
        } else {
            batchEdit.setText(model.batchName);
        }

        if (TextUtils.isEmpty(model.custType)) {
            TextView custTypeText = view.findViewById(R.id.cust_type_tv);
            custTypeText.setVisibility(View.GONE);
            custTypeEdit.setVisibility(View.GONE);
        } else {
            custTypeEdit.setText(model.custType);
        }

        callLayout.setOnClickListener(v -> {
            call(model);
        });
        saveLayout.setOnClickListener(v -> {
            saveForm(model);
        });
        sexEdit.setOnClickListener(v -> showSex1());
        statusEdit.setOnClickListener(v -> showStatus1());
        purposeEdit.setOnClickListener(v -> showPurpose1());
    }

    private void call(RecordModel model) {
        if (TextUtils.isEmpty(CallConstant.currentPhone) || (!TextUtils.isEmpty(CallConstant.currentPhone) && CallConstant.currentPhone.contains(CallConstant.NAME))) {
            getXPhone(model);
        } else {
            new XPopup.Builder(requireActivity()).asConfirm("提示", "当前手机号和坐席不一致，确定呼叫吗？", new OnConfirmListener() {
                @Override
                public void onConfirm() {
                    getXPhone(model);
                }
            }, () -> {

            }).show();
        }
    }

    /**
     * 跳转到拨号盘
     *
     * @param phoneNumber
     */
    private void jumpDial(String phoneNumber) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void closeForm() {
        if (bottomSheetDialog != null) {
            bottomSheetDialog.cancel();
        }
    }

    private void initTime() {
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.set(Calendar.HOUR_OF_DAY, 0);
        startCalendar.set(Calendar.MINUTE, 0);
        startCalendar.set(Calendar.SECOND, 0);

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.set(Calendar.HOUR_OF_DAY, 23);
        endCalendar.set(Calendar.MINUTE, 59);
        endCalendar.set(Calendar.SECOND, 59);

        long beginTime = startCalendar.getTimeInMillis();
        long endTime = endCalendar.getTimeInMillis();
        RecordModel recordModel = new RecordModel(beginTime, endTime);
        list.add(recordModel);
    }
}
